package photobox.manage

import grails.converters.JSON
import grails.transaction.Transactional
import grails.validation.ValidationException
import org.springframework.web.multipart.MultipartFile
import photobox.account.Address
import photobox.account.Member
import photobox.account.Notice
import photobox.account.Region
import photobox.account.User
import photobox.account.UserBrowse
import photobox.exception.NotFoundException
import photobox.utils.HQLUtils
import photobox.utils.PermUtils

@Transactional
class MemberService {

    def selectCustomer(searchParam, pageParam, sortParam){
        def hql = ""
        hql += " from User A where 1=1  "
        def params = [:]
        if (searchParam.id) {
            hql += " and " + HQLUtils.whereCondition("A.id", searchParam.id.opt, "id")
            params.id = searchParam.id.data
        }
        if (searchParam.username) {
            hql += " and " + HQLUtils.whereCondition("A.username", searchParam.username.opt, "username")
            params.username = searchParam.username.data
        }
        if (searchParam.nickName) {
            hql += " and " + HQLUtils.whereCondition("A.nickName", searchParam.nickName.opt, "nickName")
            params.nickName = searchParam.nickName.data
        }



        def sortHql = ""
        if (sortParam.sort) {
            sortHql = " order by A.${sortParam.sort} ${sortParam.order} "
        }
        def results = User.executeQuery("select distinct A " + hql + sortHql, params,
                [max: pageParam.pageSize, offset: pageParam.offset])
        def count = User.executeQuery("select count(distinct A.id) " + hql, params)
        return [rs:results, total:count[0]]
    }
    def saveCustomer(params) {
        def user = new User()
        user.username  = params.username?.trim()
        user.nickName = params.nickName?.trim()
        user.realName = params.realName?.trim()
        //user.password = params.password?.trim()
        //user.passwordConfirm = params.passwordConfirm
        user.passwordHash = PermUtils.mkPasswordHash(params.password)
        user.enabled = params.enabled == "on"
        user.email = params.email
        user.gender = params.int('gender')

        user.photoImage = params.photoImage
        user.presentation = params.presentation
        user.isPhotographer = params.isPhotographer as Integer

        //def userAddress = new Address()
        //users.addToAddress(userAddress)



        if (!user.save()) {
            throw new ValidationException("创建用户时发生错误", user.errors)
        }
    }
    def updateCustomer(params){
        def user = User.get(params.id)
        user.username  = params.username?.trim()
        user.nickName = params.nickName?.trim()
        user.realName = params.realName?.trim()
        if(params.password){
            user.password = params.password?.trim()
            user.passwordConfirm = params.passwordConfirm
            user.passwordHash = PermUtils.mkPasswordHash(params.password)
        }
        user.enabled = params.enabled == "on"
        user.email = params.email
        user.gender = params.int('gender')

        user.photoImage = params.photoImage
        user.presentation = params.presentation
        if(params.isPhotographer){
            user.isPhotographer = params.isPhotographer as Integer
        }

        if (!user.save()) {
            throw new ValidationException("创建用户时发生错误", user.errors)
        }
    }
    def deleteCustomer(params) {
        def user = User.get(params.id as Long)
        if (!user) {
            throw new NotFoundException("没有找到对应的管理员")
        }
        user.delete()
    }

    def selectPhotographer(searchParam, pageParam, sortParam) {
        def hql = ""
        hql += " from User A where A.isPhotographer=1 "
        def params = [:]
        if (searchParam.id) {
            hql += " and " + HQLUtils.whereCondition("A.id", searchParam.id.opt, "id")
            params.id = searchParam.id.data
        }
        if (searchParam.username) {
            hql += " and " + HQLUtils.whereCondition("A.username", searchParam.username.opt, "username")
            params.username = searchParam.username.data
        }
        if (searchParam.nickName) {
            hql += " and " + HQLUtils.whereCondition("A.nickName", searchParam.nickName.opt, "nickName")
            params.nickName = searchParam.nickName.data
        }
        def sortHql = ""
        if (sortParam.sort) {
            sortHql = " order by A.${sortParam.sort} ${sortParam.order} "
        }
        def results = User.executeQuery("select distinct A " + hql + sortHql, params,
                [max: pageParam.pageSize, offset: pageParam.offset])
        def count = User.executeQuery("select count(distinct A.id) " + hql, params)
        return [rs:results, total:count[0]]
    }
    //查询当前用户信息
    def selectUser(params) {

    }

    //注册新用户
    def createUser(params,session) {
        def member = new Member()
        member.username = params.username?.trim()
        member.nickName = params.username?.trim()
        member.password = params.password?.trim()
        member.passwordConfirm = params.passwordConfirm
        member.passwordHash = PermUtils.mkPasswordHash(params.password)
        member.enabled = params.enabled == "on"
        member.email = params.email?.trim()
        member.cellPhone = params.cellPhone?.trim()

        if (!member.save()) {
            throw new ValidationException("创建用户时发生错误",member.errors)
        }
        session.userId = member.id
        return member
    }

    def updateNoticeReaded(userId) {
        def hql = "from Notice as N where user="+userId+""
        def notice = Notice.executeQuery(hql)
        notice.each{
            if(it.isRead == 0){
                it.isRead = 1
                it.save(flush: true)
            }
        }
    }
    def saveAddress(params, userId){
        def member = Member.get(userId)
        def address = Address.findByUser(member)
        if(!address){
            address = new Address()
            address.user = member
        }

        address.province = Region.get(Integer.parseInt(params.province))
        address.city = Region.get(Integer.parseInt(params.city))
        address.district = Region.get(Integer.parseInt(params.district))
        address.postCode =params.postCode?.trim()
        address.address = params.address?.trim()
        address.consignee = params.consignee?.trim()

        if (!address.save()) {
            throw new ValidationException("更新用户时发生错误", address.errors)
        }else{
            return 1
        }
    }
    def updateUser(params, userId) {
        def member = Member.get(userId)
        if (!member) {
            throw new NotFoundException("没有找到对应的用户")
        }
        member.username = params.username?.trim()
        member.realName = params.realName?.trim()
        member.gender = Integer.parseInt(params.gender)

        def address = Address.findByUser(member)

        def province = Region.get(Integer.parseInt(params.province))
        def city = Region.get(Integer.parseInt(params.city))
        def district = Region.get(Integer.parseInt(params.district))

        if (!address) {
            address = new Address()
        }
        address.province = province
        address.city = city
        address.district = district
        address.address = params.address?.trim()
        address.postCode = params.postCode?.trim()

        member.idCardNo = params.idCardNo?.trim()
        member.presentation = params.presentation?.trim()
        member.addToAddress(address)
        if (!member.save()) {
            throw new ValidationException("更新用户时发生错误", member.errors)
        }
    }
    def loginCheck(params,session){

        if(params.username == ""){
            return [status: 0,message:'请填写用户名'] as JSON
        } else {

            def member = Member.findByUsername(params.username?.trim())
            if(member){
                if(member.passwordHash == PermUtils.mkPasswordHash(params.password?.trim())){
                    session.userId = member.id
                    session.isiPhotographer=member.isPhotographer;
                    return [status: 1,uid:member.id] as JSON
                }else{
                    return [status: 2,message:'用户名和密码不匹配'] as JSON
                }
            }else{
                return [status: 0,message:'没有此用户'] as JSON
            }
        }
    }
    def saveIcon(pictureUrl,session){
        def user = User.get(session.userId)
        user.photoImage = pictureUrl
        user.save()
    }
    def updatePassword(params,userId){

        def user = User.get(userId)

       if(!(user.passwordHash == PermUtils.mkPasswordHash(params.oldPassword))){
           return["与原密码不符"]
       }else{
           if(params.newPassword==params.passwordConfirm){
               user.passwordHash = PermUtils.mkPasswordHash(params.newPassword)
               user.passwordConfirm = params.passwordConfirm
               if (!user.save()) {
                   println(user.errors)
               }
               return ["密码修改成功"]
           }else {
               return ["两次密码不一致"]
           }
       }
    }
    def savePassword(params){
        def user = User.get(params.userId)
        if(params.password==null||params.passwordAgain==null){
            return["密码不能为空"]
        }else{
            if(params.password==params.passwordAgain) {
                user.passwordHash = PermUtils.mkPasswordHash(params.password)
                user.passwordConfirm = params.passwordAgain
                if (!user.save()) {
                    println(user.errors)
                }
                return ["密码修改成功"]
            }else{
                return ["两次密码不一致"]
            }
        }

    }
    def clearBrowserHistory(member){
       def hql = 'delete from UserBrowse userBrowse where userBrowse.user.id = '+member.id
       def sureDelete = UserBrowse.executeUpdate(hql)
       return sureDelete
    }
}
